<?php
namespace app\common\service\ai;

use Exception;

class MegaTtsService  {
    private $appid;
    private $token;
    private $host = "https://openspeech.bytedance.com";

    public function __construct($appid, $token) {
        $this->appid = $appid;
        $this->token = $token;
    }

    // 上传音频文件并开始训练
    public function train($audioPath, $spkId) {
        $url = $this->host . "/api/v1/mega_tts/audio/upload";
        $headers = [
            "Content-Type: application/json",
            "Authorization: Bearer;" . $this->token,
            "Resource-Id: volc.megatts.voiceclone"
        ];

        list($encodedData, $audioFormat) = $this->encodeAudioFile($audioPath);
        $audios = [["audio_bytes" => $encodedData, "audio_format" => $audioFormat]];

        $data = [
            "appid" => $this->appid,
            "speaker_id" => $spkId,
            "audios" => $audios,
            "source" => 2,
            "language" => 0,
            "model_type" => 1
        ];

        $response = $this->sendRequest($url, $data, $headers);

        if ($response['status_code'] != 200) {
            throw new Exception("train请求错误: " . $response['body']);
        }
        return $response['body'];
    }

    private function sendRequest($url, $data, $headers) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用证书验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 禁用主机验证
        $responseBody = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);


        return [
            'status_code' => $statusCode,
            'body' => $responseBody
        ];
    }

    // 获取训练状态
    public function getStatus($spkId) {
        $url = $this->host . "/api/v1/mega_tts/status";
        $headers = [
            "Content-Type: application/json",
            "Authorization: Bearer;" . $this->token,
            "Resource-Id: volc.megatts.voiceclone"
        ];

        $data = [
            "appid" => $this->appid,
            "speaker_id" => $spkId
        ];

        $response = $this->sendRequest($url, $data, $headers);

        echo "Response: " . $response['body'] . "\n";
    }

    // 编码音频文件为base64
    private function encodeAudioFile($filePath) {
        $audioData = file_get_contents($filePath);
        $encodedData = base64_encode($audioData);
        $audioFormat = pathinfo($filePath, PATHINFO_EXTENSION);  // 获取音频文件的扩展名
        return [$encodedData, $audioFormat];
    }

    // 发送POST请求

}

?>
